package com.hjx.windowtool.time;

import java.awt.EventQueue;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JSpinner;
import javax.swing.SpinnerNumberModel;
import javax.swing.UIManager;

import com.sun.jna.platform.win32.Kernel32;
import com.sun.jna.platform.win32.WinBase.SYSTEMTIME;

import javax.swing.SpinnerDateModel;
import java.util.Date;
import java.util.Calendar;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;

public class SetTimeApp {

	private JFrame frame;

	/**
	 * Launch the application.
	 */
	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
					SetTimeApp window = new SetTimeApp();
					window.frame.setVisible(true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	/**
	 * Create the application.
	 */
	public SetTimeApp() {
		initialize();
	}

	/**
	 * Initialize the contents of the frame.
	 */
	private void initialize() {
		frame = new JFrame();
		frame.setBounds(100, 100, 534, 377);
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		frame.getContentPane().setLayout(null);
		
		JLabel label = new JLabel("时间");
		label.setBounds(30, 55, 54, 15);
		frame.getContentPane().add(label);
		
		JSpinner spinner = new JSpinner();
		spinner.setModel(new SpinnerDateModel(new Date(1556380800000L), new Date(1556380800000L), null, Calendar.DAY_OF_YEAR));
		spinner.setBounds(68, 52, 130, 22);
		frame.getContentPane().add(spinner);
		
		JButton button = new JButton("设置");
		button.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				setLocalTime((Date) spinner.getValue());
			}
		});
		button.setBounds(208, 51, 93, 23);
		frame.getContentPane().add(button);
	}
	
	public static boolean setLocalTime(Date time){
		SYSTEMTIME lpSystemTime=new SYSTEMTIME();
		Calendar cal = Calendar.getInstance();
        cal.setTimeInMillis(time.getTime());
        lpSystemTime.wYear = (short) cal.get(Calendar.YEAR);
        lpSystemTime.wMonth = (short) (1 + cal.get(Calendar.MONTH) - Calendar.JANUARY);  // 1 = January
        lpSystemTime.wDay = (short) cal.get(Calendar.DAY_OF_MONTH);
        lpSystemTime.wHour = (short) cal.get(Calendar.HOUR_OF_DAY);
        lpSystemTime.wMinute = (short) cal.get(Calendar.MINUTE);
        lpSystemTime.wSecond = (short) cal.get(Calendar.SECOND);
        lpSystemTime.wMilliseconds = (short) cal.get(Calendar.MILLISECOND);
        lpSystemTime.wDayOfWeek = (short) (cal.get(Calendar.DAY_OF_WEEK) - Calendar.SUNDAY); // 0 = Sunday
		
		return Kernel32.INSTANCE.SetLocalTime(lpSystemTime);
	}
}
